﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Entity;
using DAL;
using Common;
using System.Data.Linq;
using System.Linq.Expressions;
using System.Data.Linq.SqlClient;
namespace BAL
{


    public class Question
    {


        public static IList<QuestionInfo> GetQuestions(int examPaperId, string title,
            string score, string quesiontTypeId, string subjectId, string gradeId, string knowId,
            string keyWord, string diffId, string bookId, int first, int max)
        {
            using (var db = DatabaseHelper.GetDashboardData())
            {

                var query = from questionItem in db.GetTable<Models.Question>()
                            from paperQuesItem in db.GetTable<Models.Paper_Ques>()
                            where questionItem.Id == paperQuesItem.QuesId
                            && paperQuesItem.ExamPaperId == examPaperId && questionItem.StatusId == 5
                            orderby questionItem.QuesTypeId, questionItem.Score descending, paperQuesItem.OrderId ascending 
                            select questionItem;
                if (keyWord != null && keyWord != "")
                {
                    query = query.Where(p => SqlMethods.Like(p.KeyWord, "%" + keyWord + "%"));
                }
                if (title != null && title != "")
                {
                    query = query.Where(p => SqlMethods.Like(p.Title, "%" + title + "%"));
                }
                if (score != null && score != "")
                {
                    query = query.Where(p => p.Score == decimal.Parse(score));
                }
                if (quesiontTypeId != null && quesiontTypeId != "" && quesiontTypeId != "0")
                {
                    query = query.Where(p => p.QuesTypeId == int.Parse(quesiontTypeId));
                }
                if (subjectId != null && subjectId != "" && subjectId != "0")
                {
                    query = query.Where(p => p.SubjectId == int.Parse(subjectId));
                }
                if (gradeId != null && gradeId != "" && gradeId != "0")
                {
                    query = query.Where(p => p.GradeId.HasValue && p.GradeId == int.Parse(gradeId));
                }
                if (knowId != null && knowId != "" && knowId != "0")
                {
                    query = query.Where(p => p.KnowId == int.Parse(knowId));
                }
                if (bookId != null && bookId != "" && bookId != "0")
                {
                    query = query.Where(p => p.BookId == int.Parse(bookId));
                }
                if (max > 0)
                {
                    return query.Skip(first).Take(max).Select(c => TransQuestion2QuestionInfo(c)).ToList<QuestionInfo>();
                }
                else
                {
                    return query.Select(c => TransQuestion2QuestionInfo(c)).ToList<QuestionInfo>();
                }
            }
        }
        public static int GetQuestionsCount(int examPaperId, string title,
            string score, string quesiontTypeId, string subjectId, string gradeId, string knowId,
            string keyWord, string diffId, string bookId)
        {
            using (var db = DatabaseHelper.GetDashboardData())
            {

                var query = from questionItem in db.GetTable<Models.Question>()
                            from paperQuesItem in db.GetTable<Models.Paper_Ques>()
                            where questionItem.Id == paperQuesItem.QuesId
                            && paperQuesItem.ExamPaperId == examPaperId && questionItem.StatusId == 5
                            select questionItem;
                if (keyWord != null && keyWord != "")
                {
                    query = query.Where(p => SqlMethods.Like(p.KeyWord, "%" + keyWord + "%"));
                }
                if (title != null && title != "")
                {
                    query = query.Where(p => SqlMethods.Like(p.Title, "%" + title + "%"));
                }
                if (score != null && score != "")
                {
                    query = query.Where(p => p.Score == decimal.Parse(score));
                }
                if (quesiontTypeId != null && quesiontTypeId != "" && quesiontTypeId != "0")
                {
                    query = query.Where(p => p.QuesTypeId == int.Parse(quesiontTypeId));
                }
                if (subjectId != null && subjectId != "" && subjectId != "0")
                {
                    query = query.Where(p => p.SubjectId == int.Parse(subjectId));
                }
                if (gradeId != null && gradeId != "" && gradeId != "0")
                {
                    query = query.Where(p => p.GradeId.HasValue && p.GradeId == int.Parse(gradeId));
                }
                if (knowId != null && knowId != "" && knowId != "0")
                {
                    query = query.Where(p => p.KnowId == int.Parse(knowId));
                }
                if (bookId != null && bookId != "" && bookId != "0")
                {
                    query = query.Where(p => p.BookId == int.Parse(bookId));
                }

                return query.Count();

            }
        }

        public static IList<QuestionInfo> GetQuestionsNotExamPaperId(int examPaperId, string title, decimal score, int quesiontTypeId, int subjectId, int gradeId, int knowId, string keyWord, int diffId, int bookId, int first, int max)
        {
            return GetQuestionsNotExamPaperId(examPaperId, title, score, quesiontTypeId, subjectId, gradeId, knowId, keyWord, diffId, bookId, Module_File.GetConfig(), first, max);
        }

        public static IList<QuestionInfo> GetQuestionsNotExamPaperId(int examPaperId, string title,
            decimal score, int quesiontTypeId, int subjectId, int gradeId, int knowId,
            string keyWord, int diffId, int bookId,string StatusIdList, int first, int max)
        {
            using (var db = DatabaseHelper.GetDashboardData())
            {

                var query = from questionItem in db.GetTable<Models.Question>()
                            where
                            !
                           (from paperQuesItem in db.GetTable<Models.Paper_Ques>()
                            where paperQuesItem.ExamPaperId == examPaperId
                            select paperQuesItem.QuesId
                           ).Contains(questionItem.Id) && questionItem.StatusId == 5
                            select questionItem;
                if (!PageValidate.IsEmpty(StatusIdList))
                {
                    if (StatusIdList.IndexOf(",") == -1)
                    {
                        query = query.Where(p => p.StatusId == int.Parse(StatusIdList));
                    }
                    else
                    {
                        string[] p = StatusIdList.Split(new char[] { ',' });
                        if (p.Count() > 0)
                        {
                            query = query.Where(t => GetArray<int>.Get(ArrayHelper.ConvertToIntArray(p)).Contains(t.StatusId));
                        }
                    }
                }
                if (keyWord != null && keyWord != "")
                {
                    query = query.Where(p => SqlMethods.Like(p.KeyWord, "%" + keyWord + "%"));
                }
                if (title != null && title != "")
                {
                    query = query.Where(p => SqlMethods.Like(p.Title, "%" + title + "%"));
                }
                if (score > 0)
                {
                    query = query.Where(p => p.Score == score);
                }
                if (quesiontTypeId > 0)
                {
                    query = query.Where(p => p.QuesTypeId == quesiontTypeId);
                }
                if (subjectId > 0)
                {
                    query = query.Where(p => p.SubjectId == subjectId);
                }
                if (gradeId > 0)
                {
                    query = query.Where(p => p.GradeId.HasValue && p.GradeId == gradeId);
                }
                if (diffId > 0)
                {
                    query = query.Where(p => p.DifficId == diffId);
                }
                if (knowId > 0)
                {
                    query = query.Where(p => p.KnowId == knowId);
                }
                if (bookId > 0)
                {
                    query = query.Where(p =>SqlMethods.Like(p.ROC,"%"+bookId.ToString()+"%"));
                }
                if (max > 0)
                {
                    return query.OrderBy(p => p.QuesTypeId).Skip(first).Take(max).Select(c => TransQuestion2QuestionInfo(c)).ToList<QuestionInfo>();
                }
                else
                {
                    return query.OrderBy(p => p.QuesTypeId).Select(c => TransQuestion2QuestionInfo(c)).ToList<QuestionInfo>();
                }
            }
        }
        public static int GetQuestionsNotExamPaperIdCount(int examPaperId, string title,
           decimal score, int quesiontTypeId, int subjectId, int gradeId, int knowId,
           string keyWord, int diffId, int bookId)
        {
            return GetQuestionsNotExamPaperIdCount(examPaperId, title, score, quesiontTypeId, subjectId, gradeId, knowId, keyWord, diffId, bookId, Module_File.GetConfig());
        }
        public static int GetQuestionsNotExamPaperIdCount(int examPaperId, string title,
           decimal score, int quesiontTypeId, int subjectId, int gradeId, int knowId,
           string keyWord, int diffId, int bookId,string StatusIdList)
        {
            using (var db = DatabaseHelper.GetDashboardData())
            {

                var query = from questionItem in db.GetTable<Models.Question>()
                            where
                            !
                           (from paperQuesItem in db.GetTable<Models.Paper_Ques>()
                            where paperQuesItem.ExamPaperId == examPaperId
                            select paperQuesItem.QuesId
                           ).Contains(questionItem.Id) && questionItem.StatusId == 5
                            select questionItem;
                if (!PageValidate.IsEmpty(StatusIdList))
                {
                    if (StatusIdList.IndexOf(",") == -1)
                    {
                        query = query.Where(p => p.StatusId == int.Parse(StatusIdList)); 
                    }
                    else
                    {
                        string[] p = StatusIdList.Split(new char[] { ',' });
                        if (p.Count() > 0)
                        {
                            query = query.Where(t => GetArray<int>.Get(ArrayHelper.ConvertToIntArray(p)).Contains(t.StatusId));
                        }
                    }
                }

                if (keyWord != null && keyWord != "")
                {
                    query = query.Where(p => SqlMethods.Like(p.KeyWord, "%" + keyWord + "%"));
                }
                if (title != null && title != "")
                {
                    query = query.Where(p => SqlMethods.Like(p.Title, "%" + title + "%"));
                }
                if (score > 0)
                {
                    query = query.Where(p => p.Score == score);
                }
                if (quesiontTypeId > 0)
                {
                    query = query.Where(p => p.QuesTypeId == quesiontTypeId);
                }
                if (subjectId > 0)
                {
                    query = query.Where(p => p.SubjectId == subjectId);
                }
                if (gradeId > 0)
                {
                    query = query.Where(p => p.GradeId.HasValue && p.GradeId == gradeId);
                }
                if (knowId > 0)
                {
                    query = query.Where(p => p.KnowId == knowId);
                }
                if (diffId > 0)
                {
                    query = query.Where(p => p.DifficId== diffId);
                }
                if (bookId > 0)
                {
                    query = query.Where(p => SqlMethods.Like(p.ROC, "%" + bookId.ToString() + "%"));
                }
                return query.Count();
            }
        }

        internal static QuestionInfo TransQuestion2QuestionInfo(Models.Question question)
        {
            QuestionInfo questionInfo = new QuestionInfo();

            Utility.SetObjectValueWithTheSamePropertyName(questionInfo, question);

            return questionInfo;
        }

        public static QuestionInfo AddQuestion(QuestionInfo questionInfo)
        {
            using (var db = DatabaseHelper.GetDashboardData())
            {
                Models.Question question = new Models.Question();
                Utility.SetObjectValueWithTheSamePropertyName(question, questionInfo);
                DatabaseHelper.Insert<Models.Question>(question);
                return TransQuestion2QuestionInfo(question);
            }
        }

        public static void EditQuestion(QuestionInfo questionInfo)
        {
            using (var db = DatabaseHelper.GetDashboardData())
            {
                try
                {
                    Models.Question question = db.Questions.Single(b => b.Id == questionInfo.Id);

                    Utility.SetObjectValueWithTheSamePropertyName(question, questionInfo);

                    db.SubmitChanges(ConflictMode.ContinueOnConflict);
                }
                catch (ChangeConflictException)
                {
                    foreach (ObjectChangeConflict occ in db.ChangeConflicts)
                    {
                        occ.Resolve(RefreshMode.KeepCurrentValues);
                    }
                }
            }
        }

        /// <summary>
        /// 更新用户ID
        /// </summary>
        /// <param name="Userid1">原来的ID</param>
        /// <param name="Userid2">新的ID</param>
        public static void SetUserId(int Userid1, int Userid2)
        {
            using (var db = DatabaseHelper.GetDashboardData())
            {
                string sql = string.Format("update Questions set Userid={1}  where Userid={0}", Userid1, Userid2);
                db.ExecuteCommand(sql);
            }
        }

        public static int GetQuestionCount(QuestionInfo qinfo)
        {
            return GetQuestionCount(qinfo, "", "", "");
        }
        
        public static int GetQuestionCount(QuestionInfo qinfo, string QuestionTypeList, string SubjectList, string UserIdList)
        {
            DateTime? startDate = null;
            DateTime? endDate = null;
            return GetQuestionCount(qinfo, QuestionTypeList, SubjectList, UserIdList, startDate, endDate);
        }

        public static int GetQuestionCount(QuestionInfo qinfo, string QuestionTypeList, string SubjectList, string UserIdList, DateTime? StartDate, DateTime? EndDate)
        {
            using (var db = DatabaseHelper.GetDashboardData())
            {
                return db.Questions.Where(GetQuestionExpression(qinfo, QuestionTypeList, SubjectList, UserIdList,StartDate,EndDate)).Count();
            }
        }

        public static int GetQuestionCount(int questype, int subject, string auth, string keyword, int state, int userid)
        {
            using (var db = DatabaseHelper.GetDashboardData())
            {
                return db.Questions.Where(GetQuestionExpression(questype, subject, auth, keyword, state, userid)).Count();
            }
        }

        public static IList<QuestionInfo> GetQuestionInfofs(QuestionInfo qinfo,int first, int max)
        {
            return GetQuestionInfofs(qinfo, "", "", "", first, max);
        }

        public static IList<QuestionInfo> GetQuestionInfofs(QuestionInfo qinfo, string QuestionTypeList, string SubjectList, string UserIdList, int first, int max)
        {
            DateTime? startDate = null;
            DateTime? endDate = null;
            return GetQuestionInfofs(qinfo, QuestionTypeList, SubjectList, UserIdList, startDate, endDate, first, max);
        }
        
        public static IList<QuestionInfo> GetQuestionInfofs(QuestionInfo qinfo, string QuestionTypeList, string SubjectList, string UserIdList, DateTime? StartDate, DateTime? EndDate, int first, int max)
        {
            using (var db = DatabaseHelper.GetDashboardData())
            {
                var d = db.Questions.OrderByDescending(t => t.Id).Where(GetQuestionExpression(qinfo, QuestionTypeList, SubjectList, UserIdList, StartDate, EndDate));
                if (max > 0)
                {
                    return d.Select(w => TransQuestion2QuestionInfo(w)).Skip(first).Take(max).ToList();
                }
                else
                {
                    return d.Select(w => TransQuestion2QuestionInfo(w)).ToList();
                }
            }
        }
        
        public static IList<QuestionInfo> GetQuestionInfofs(int questype, int subject, string auth, string keyword, int state, int userid, int first, int max)
        {
            using (var db = DatabaseHelper.GetDashboardData())
            {
                var d = db.Questions.OrderByDescending(t => t.Id).Where(GetQuestionExpression(questype, subject, auth, keyword, state, userid));
                if (max > 0)
                {
                    return d.Select(w => TransQuestion2QuestionInfo(w)).Skip(first).Take(max).ToList();
                }
                else
                {
                    return d.Select(w => TransQuestion2QuestionInfo(w)).ToList();
                }
            }
        }
        
        private static Expression<Func<Models.Question, bool>> GetQuestionExpression(QuestionInfo qinfo)
        {
            return GetQuestionExpression(qinfo, "", "", "");
        }

        private static Expression<Func<Models.Question, bool>> GetQuestionExpression(QuestionInfo qinfo, string QuestionTypeList, string SubjectList, string UserIdList)
        {
            DateTime? startDate = null;
            DateTime? endDate = null;
            return GetQuestionExpression(qinfo, QuestionTypeList, SubjectList, UserIdList, startDate, endDate);
        }
        
        private static Expression<Func<Models.Question, bool>> GetQuestionExpression(QuestionInfo qinfo, string QuestionTypeList, string SubjectList, string UserIdList, DateTime? StartDate,DateTime? EndDate)
        {
            var predicate = PredicateBuilder.True<Models.Question>();
            if (qinfo.QuesTypeId > 0)
            {
                predicate = predicate.And(p => p.QuesTypeId == qinfo.QuesTypeId);
            }
            if (qinfo.SubjectId > 0)
            {
                predicate = predicate.And(p => p.SubjectId == qinfo.SubjectId);
            }
            if (qinfo.StatusId > 0)
            {
                predicate = predicate.And(p => p.StatusId == qinfo.StatusId);
            }
            if (qinfo.UserId > 0)
            {
                predicate = predicate.And(p => p.UserId == qinfo.UserId);
            }
            if (qinfo.CognitiveLevelId > 0)
            {
                predicate = predicate.And(p => p.CognitiveLevelId == qinfo.CognitiveLevelId);
            }
            if (qinfo.DifficId > 0)
            {
                predicate = predicate.And(p => p.DifficId == qinfo.DifficId);
            }
            if (qinfo.KnowId > 0)
            {
                predicate = predicate.And(p => p.KnowId == qinfo.KnowId);
            }
            if (qinfo.Score > 0)
            {
                predicate = predicate.And(p => p.Score == qinfo.Score);
            }
            if (qinfo.ComputeTime > 0)
            {
                predicate = predicate.And(p => p.ComputeTime == qinfo.ComputeTime);
            }
            if (qinfo.BookId > 0)
            {
                predicate = predicate.And(p => ("," + p.ROC + ",").Contains("," + qinfo.BookId + ","));
            }
            if (qinfo.Printer != null && qinfo.Printer != "")
            {
                predicate = predicate.And(p => p.Printer.Contains(qinfo.Printer));
            }
            if (qinfo.KeyWord != null && qinfo.KeyWord != "")
            {
                predicate = predicate.And(p => p.KeyWord.Contains(qinfo.KeyWord));
            }
            if (!PageValidate.IsEmpty(QuestionTypeList))
            {
                predicate = predicate.And(p => ArrayHelper.ConvertToIntArray(Module_String.splitstr(QuestionTypeList, ",")).Contains(p.QuesTypeId));
            }

            if (!PageValidate.IsEmpty(SubjectList))
            {
                predicate = predicate.And(p => ArrayHelper.ConvertToIntArray(Module_String.splitstr(SubjectList, ",")).Contains(p.SubjectId));
            }

            if (!PageValidate.IsEmpty(UserIdList))
            {
                predicate = predicate.And(p => ArrayHelper.ConvertToIntArray(Module_String.splitstr(UserIdList, ",")).Contains(p.UserId));
            }
            if (StartDate != null)
            {
                predicate = predicate.And(p => p.CreateDate >= StartDate);
            }
            if (EndDate != null)
            {
                predicate = predicate.And(p => p.CreateDate <= EndDate);
            }
            return predicate;
        }

        private static Expression<Func<Models.Question, bool>> GetQuestionExpression(int questype, int subject, string auth, string keyword, int state, int userid)
        {
            var predicate = PredicateBuilder.True<Models.Question>();
            if (questype > 0)
                predicate = predicate.And(p => p.QuesTypeId == questype);
            if (subject > 0)
                predicate = predicate.And(p => p.SubjectId == subject);
            if (state > 0)
                predicate = predicate.And(p => p.StatusId == state);
            if (userid > 0)
                predicate = predicate.And(p => p.UserId == userid);
            auth = (auth ?? string.Empty).Trim();
            if (!string.IsNullOrEmpty(auth))
                predicate = predicate.And(p => p.Printer.Contains(auth));
            if (keyword.Trim() != "")
            {
                predicate = predicate.And(p => p.Serial.Contains(keyword) || p.KeyWord.Contains(keyword));
            }

            return predicate;
        }

        public static void DelQuestion(int id)
        {
            using (var db = DatabaseHelper.GetDashboardData())
            {
                DelQuestion(new int[] { id });
            }
        }

        public static void DelQuestion(int[] lstId)
        {
            using (var db = DatabaseHelper.GetDashboardData())
            {
                if (lstId.Length > 0)
                {
                    string sql = string.Format("delete from Questions where id in ({0})", string.Join(",", lstId.ConvertToStringArray()));
                    db.ExecuteCommand(sql);
                }
            }
        }

        public static void DelQuestionByBook(int BookID)
        {
            using (var db = DatabaseHelper.GetDashboardData())
            {
                int[] ids = db.Questions.Where(t => ("," + t.ROC + ",").Contains("," + BookID + ",")).Select(t => t.Id).ToArray();
                DelQuestion(ids);
            }
        }

        public static void DelQuestionByDiffic(int DifficID)
        {
            using (var db = DatabaseHelper.GetDashboardData())
            {
                int[] ids = db.Questions.Where(t => t.DifficId == DifficID).Select(t => t.Id).ToArray();
                DelQuestion(ids);
            }
        }

        public static void DelQuestionByAssess(int AssessID)
        {
            using (var db = DatabaseHelper.GetDashboardData())
            {
                int[] ids = db.Questions.Where(t => t.AssessId == AssessID).Select(t => t.Id).ToArray();
                DelQuestion(ids);
            }
        }

        public static void DelQuestionByKnowledge(int KnowledgeID)
        {
            using (var db = DatabaseHelper.GetDashboardData())
            {
                int[] ids = db.Questions.Where(t => t.KnowId == KnowledgeID).Select(t => t.Id).ToArray();
                DelQuestion(ids);
            }
        }

        public static void DelQuestionByCognitiveLevel(int CognitiveLevelID)
        {
            using (var db = DatabaseHelper.GetDashboardData())
            {
                int[] ids = db.Questions.Where(t => t.CognitiveLevelId == CognitiveLevelID).Select(t => t.Id).ToArray();
                DelQuestion(ids);
            }
        }

        public static void DelQuestionByQuesType(int QuesTypeID)
        {
            using (var db = DatabaseHelper.GetDashboardData())
            {
                int[] ids = db.Questions.Where(t => t.QuesTypeId == QuesTypeID).Select(t => t.Id).ToArray();
                DelQuestion(ids);
            }
        }

        public static QuestionInfo GetQuestionInfoById(int Id)
        {
            using (var db = DatabaseHelper.GetDashboardData())
            {
                Models.Question question = db.Questions.Single(b => b.Id == Id);
                return TransQuestion2QuestionInfo(question);
            }
        }

        public static bool CheckQuestionExistById(int Id)
        {
            using (var db = DatabaseHelper.GetDashboardData())
            {
                return db.Questions.Where(w => w.Id == Id).Count() > 0;
            }
        }

        public static bool CheckQuestionExistByName(string title)
        {
            using (var db = DatabaseHelper.GetDashboardData())
            {
                return db.Questions.Where(w => w.Title == title).Count() > 0;
            }
        }

        public static int CheckQuestionCountBySubject(int SubjectId)
        {
            using (var db = DatabaseHelper.GetDashboardData())
            {
                return db.Questions.Where(t => t.SubjectId == SubjectId).Count();
            }
        }

        //通过课程的subjectId查询题目的集合
        public static IList<QuestionInfo> getQuestionListBySubject(List<int> subjects, int first, int max)
        {
            using (var db = DatabaseHelper.GetDashboardData())
            {

                //IList<Models.Question> lista =new List<Models.Question>();
                IList<QuestionInfo> infos = db.GetTable<Models.Question>().Where(t => GetArray<int>.Get(subjects).Contains(t.SubjectId)).Select(t => TransQuestion2QuestionInfo(t)).ToList();

                if (max > 0)
                {
                    return infos.Select(w => w).Skip(first).Take(max).ToList();
                }
                else
                {
                    List<QuestionInfo> aa = infos.Select(w => w).ToList();
                    return aa;
                }
            }
        }
        //通过课程的subjectId查询题目数量
        /*  public static int getQuestionConutBySubject(List<int> subject) 
          {
              using (var db = DatabaseHelper.GetDashboardData()) 
              {
                  int sum = 0;
                  for (int i = 0; i < subject.Count;i++ )
                  {
                      sum += db.Questions.Where(t => t.SubjectId == subject[i]).Count();
                  }
                  return sum;
              }
          }*/
        public static int getQuestionConutBySubject(int subject)
        {
            using (var db = DatabaseHelper.GetDashboardData())
            {
                return db.Questions.Where(t => t.SubjectId == subject).Count();
            }
        }
        public static int CheckQuestionCountByKnow(int KnowId)
        {
            using (var db = DatabaseHelper.GetDashboardData())
            {
                return db.Questions.Where(t => t.KnowId == KnowId).Count();
            }
        }

        public static int CheckQuestionCountByStatus(int StatusId)
        {
            using (var db = DatabaseHelper.GetDashboardData())
            {
                return db.Questions.Where(t => t.StatusId == StatusId).Count();
            }
        }

        public static int CheckQuestionCountByUser(int UserId)
        {
            using (var db = DatabaseHelper.GetDashboardData())
            {
                return db.Questions.Where(t => t.UserId == UserId).Count();
            }
        }

        public static int CheckQuestionCountByDiffic(int DifficId)
        {
            using (var db = DatabaseHelper.GetDashboardData())
            {
                return db.Questions.Where(t => t.DifficId == DifficId).Count();
            }
        }

        public static int CheckQuestionCountByLevel(int LevelId)
        {
            using (var db = DatabaseHelper.GetDashboardData())
            {
                return db.Questions.Where(t => t.LevelId == LevelId).Count();
            }
        }

        public static int CheckQuestionCountByBook(int BookId)
        {
            using (var db = DatabaseHelper.GetDashboardData())
            {
                return db.Questions.Where(t => t.BookId == BookId).Count();
            }
        }

        public static int CheckQuestionCountByAssess(int AssessId)
        {
            using (var db = DatabaseHelper.GetDashboardData())
            {
                return db.Questions.Where(t => t.AssessId == AssessId).Count();
            }
        }

        public static int CheckQuestionCountByQuesType(int QuesTypeId)
        {
            using (var db = DatabaseHelper.GetDashboardData())
            {
                return db.Questions.Where(t => t.QuesTypeId == QuesTypeId).Count();
            }
        }

        //public static int GetQuestionCount(QuestionInfo questioninfo)
        //{
        //    using (var db = DatabaseHelper.GetDashboardData())
        //    {
        //        return db.Questions.Where(t => t.KnowId == questioninfo.KnowId && t.QuesTypeId == questioninfo.QuesTypeId).Count(); 
        //    }
        //}

        public static int GetQuestionMax(QuestionInfo questioninfo)
        {
            try
            {
                using (var db = DatabaseHelper.GetDashboardData())
                {
                    return Convert.ToInt32(db.Questions.Where(t => t.KnowId == questioninfo.KnowId && t.QuesTypeId == questioninfo.QuesTypeId).Select(t => t.Counts).Max());
                }
            }
            catch
            {
                return 0;
            }
        }

        public static IList<PaperQuestionInfo> GetList(int Paperid)
        {
            using (var db = DatabaseHelper.GetDashboardData())
            {
                var query = from t in db.Paper_Ques
                            join t01 in db.Questions on new { QuesId = t.QuesId } equals new { QuesId = t01.Id }
                            join t0 in db.Diffics on new { DifficId = t01.DifficId } equals new { DifficId = t0.Id }
                            where
                              t.ExamPaperId == Paperid
                            orderby
                              t.OrderId,
                              t01.Score,
                              t0.Keyword
                            select new
                            {
                                t.OrderId,
                                t01.Id,
                                t01.Title,
                                t01.Score,
                                t01.KnowId,
                                t.ExamPaperId,
                                t01.QuesTypeId,
                                t01.Answer,
                                t.SubPolicyId,
                                Diffic = int.Parse(t0.Keyword)
                            };
                IList<PaperQuestionInfo> PaperQuestion_Info = new List<PaperQuestionInfo>();
                foreach (var r in query)
                {
                    PaperQuestion_Info.Add(new PaperQuestionInfo { Id = r.Id, Diffic = r.Diffic, ExamPaperId = r.ExamPaperId, KnowId = r.KnowId, OrderId = r.OrderId, Score = r.Score, Title = r.Title, QuesTypeId = r.QuesTypeId, Answer = r.Answer, SubPolicyId = r.SubPolicyId });
                }
                return PaperQuestion_Info;
            }
        }
        public static string GetLog(string Remark)
        {
            if (PageValidate.IsEmpty(Remark))
            {
                return "";
            }
            if (Remark.IndexOf("<ET:Split/>") == -1)
            {
                return "";
            }
            return Module_String.splitstr(Remark, "<ET:Split/>")[1];
        }
        public static IList<QuestionStatusInfo> GetQuestionDic(DateTime? StartDate, DateTime? EndDate)
        {
            int subjectId = 0;
            int statusId = 0;
            return GetQuestionDic(StartDate, EndDate, subjectId, statusId);
        }

 

 
    public static IList<QuestionStatusInfo> GetQuestionDic(DateTime? StartDate, DateTime? EndDate, int SubjectId, int StatusId)
    {
        using (var db= DatabaseHelper.GetDashboardData())
        {
            //var source = db.Questions.Select(t=>t.Id);
            var query = from t in db.Questions
                        select new { 
                            t.Id,
                            t.Printer,
                            t.StatusId,
                            t.SubjectId,
                            t.PrinterId,
                            t.CreateDate
                        };
            if (SubjectId > 0)
            {
                query = query.Where(t => t.SubjectId == SubjectId);
                //source = source.Where(s=>s.
            }
            if (StatusId > 0)
            {
                query = query.Where(t => t.StatusId == StatusId);
                //source = source.Where(Expression.Lambda(Expression.Equal(Expression.Property(expression = Expression.Parameter(typeof(<>f__AnonymousType3<int, int, DateTime, string, int, int>), "t"), (MethodInfo) methodof(<>f__AnonymousType3<int, int, DateTime, string, int, int>.get_StatusId, <>f__AnonymousType3<int, int, DateTime, string, int, int>)), Expression.Constant(StatusId)), new ParameterExpression[] { expression }));
            }
            if (StartDate != null)
            {
                query = query.Where(t=>t.CreateDate >= StartDate);
                //source = source.Where(Expression.Lambda(Expression.GreaterThanOrEqual(Expression.Property(expression = Expression.Parameter(typeof(<>f__AnonymousType3<int, int, DateTime, string, int, int>), "t"), (MethodInfo) methodof(<>f__AnonymousType3<int, int, DateTime, string, int, int>.get_CreateDate, <>f__AnonymousType3<int, int, DateTime, string, int, int>)), Expression.Property(Expression.Constant(StartDate), (MethodInfo) methodof(DateTime?.get_Value, DateTime?)), false, (MethodInfo) methodof(DateTime.op_GreaterThanOrEqual)), new ParameterExpression[] { expression }));
            }
            if (EndDate != null)
            {
                query = query.Where(t => t.CreateDate <= EndDate);
                //source = source.Where(Expression.Lambda(Expression.LessThanOrEqual(Expression.Property(expression = Expression.Parameter(typeof(<>f__AnonymousType3<int, int, DateTime, string, int, int>), "t"), (MethodInfo) methodof(<>f__AnonymousType3<int, int, DateTime, string, int, int>.get_CreateDate, <>f__AnonymousType3<int, int, DateTime, string, int, int>)), Expression.Property(Expression.Constant(EndDate), (MethodInfo) methodof(DateTime?.get_Value, DateTime?)), false, (MethodInfo) methodof(DateTime.op_LessThanOrEqual)), new ParameterExpression[] { expression }));
            }
            IList<QuestionStatusInfo> list = new List<QuestionStatusInfo>();
            foreach (var type in query)
            {
                list.Add(new QuestionStatusInfo(type.Id, type.Printer, type.StatusId, type.SubjectId, type.PrinterId));
            }
            return list;
        }
    }

 


        /// <summary>
        /// 根据ID列表读取数据
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public static IList<QuestionInfo> GetList(IList<int> ids)
        {
            using (var db = DatabaseHelper.GetDashboardData())
            {
                return db.GetTable<Models.Question>().Where(t => GetArray<int>.Get(ids).Contains(t.Id)).Select(t => TransQuestion2QuestionInfo(t)).ToList();
            }
        }
    }
}